-- hp_to_transform
-- created by chendh
-- 血量低于百分比时切换形态

return {
    -- 返回的是提升的攻击点数
    apply = function(prop, baseValue)
        return prop[3];
    end,

    trigger = function(who, prop)
        local rate = math.modf(1000 * who:queryAttrib("hp") / who:queryAttrib("max_hp"));
        local value = tonumber(prop[2]);

        if rate >= value then
            return;
        end

        local classId = who:getClassId();

        -- 如果配置了威慑的怪物，对方在在场时，无法变身（例如：狼人在场时，血奴无法变身）
        local dbase = MonsterM.query(classId, "dbase");
        if type(dbase["fear_monster_id"]) == "number" then
            if DungeonM.isMonsterAlive(dbase["fear_monster_id"]) then
                trace("hp_to_transform", "威慑怪物(%d)在场，怪物(%d)无法变身。",
                    dbase["fear_monster_id"], classId);
                return;
            end
        end

        local receive_hp = dbase["transform_receive_hp"] or 0;
        local receive_attack = dbase["transform_receive_attack"] or 0;

        -- 怪物变身
        -- 修改class_id, 技能
        local toClassId = prop[3];
        who:setClassId(toClassId);
        who.dbase:set("class_id", toClassId);
        local skills = MonsterM.query(toClassId, "skills");
        who.dbase:set("skills", skills);

        -- 先去掉DEBUFF
        PropM.deleteProp(who, "debuff");
        PropM.deleteProp(who, "special");

        -- 恢复血量
        local hp = math.floor(receive_hp * who:queryAttrib("max_hp") / 1000);

        -- 此时怪物的血量可能为负数了，需要修正一下
        hp = math.max(who.dbase:query("hp", 0) + hp, hp);
        who.dbase:set("hp", hp);

        -- 变身需要提升攻击%
        local attack = math.floor(receive_attack * who:queryAttrib("attack") / 1000);
        who:addAttrib("attack", attack);

        -- 重置出现回合
        local grid = DungeonM.getGridByPos(who:getPos());
        grid.openRound = CombatM.getRound();

        -- 刷新属性
        PropM.refresh(who);

        -- 如果被变形了，需要清空变形的参数
        if who.dbase:query("changeClassId") then
            who.dbase:delete("changeClassId");
        end

        -- 有变身的状态，那么清空
        CombatStatusM.clearStatus(who, "transfiguration");

        -- 清除禁锢抗性
        CombatStatusM.clearStatus(who, "durance_resist");

        -- 抛出变身事件
        EventMgr.fire(event.MONSTER_TRANSFORM, {["pos"] = who:getPos(), ["class_id"] = toClassId, });
    end,

    record = function(target, prop, path)
        return false;
    end
};